import 'dart:async';
import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:mtf/app/net/HttpManger.dart';
import 'package:mtf/app/routes/app_pages.dart';
import 'package:mtf/app/utils/AppUtils.dart';
import 'package:mtf/app/utils/cache/AppCahche.dart';
import 'package:mtf/app/utils/cache/CacheUtil.dart';
import 'package:package_info/package_info.dart';
import 'package:r_upgrade/r_upgrade.dart';
import 'package:flutter_update_dialog/flutter_update_dialog.dart';

import '../../../R.dart';
import '../../data/VersionBeanEntity.dart';
/**
 * GetX Template Generator - fb.com/htngu.99
 * */

class settingController extends GetxController {
  var cacheSize = "".obs;

  var versionObs = "".obs;

  void clickMineInfo() {
    Get.toNamed(Routes.MINE_INFO);
  }

  void clickChangePsw() {
    Get.toNamed(Routes.CHANGE_PSW);
  }

  void clickBankManager() {
    AppUtils.authAndMt5Check((){
      Get.toNamed(Routes.BANK_MANAGER);
    });

  }

  void clickLogout() async {
    AppCache.exitLogin();
  }

  @override
  void onInit() {
    super.onInit();
    getCacheSize();
    registerProgress();
    versionGet();
  }

  void getCacheSize() async {
    var size = await CacheUtil.loadCache();
    cacheSize.value = size.toString();
  }

  void cleanSize() async {
    await CacheUtil.clearCache();
    getCacheSize();
  }

  Future<String> versionGet() async {
    var tempVersion = "1.0.0";
    if (Platform.isAndroid) {
      var version = await android();
      tempVersion = version;
    } else if (Platform.isIOS) {
      var version = await ios();
      tempVersion = version;
    }
    versionObs.value = "v${tempVersion}";
    return tempVersion;
    // RUpgrade.getVersionFromAppStore('414478124');
    // RUpgrade.getVersionFromAndroidStore(
    //     AndroidStore.TENCENT);
  }

  void updateApp() async {
    var version = await versionGet();
    if (Platform.isAndroid) {
      var resp = await HttpManager.reqVersion();
      if (resp.isSuccessData()) {
        var newsVersion = resp.data!.version;
        var isUpdate = isUpdateApp(version, newsVersion);
        if (isUpdate) {
          customStyle(resp.data!!);
        } else {
          SmartDialog.showToast("已经是最新版本。");
        }
      }
    }else if(Platform.isIOS){
      String appName = await RUpgrade.getVersionFromAppStore('414478124') ??"1.00";
      print('ios ${appName}');
      var isUpdate = isUpdateApp(version, appName);
      if (isUpdate) {
        RUpgrade.upgradeFromUrl("https://apps.apple.com/cn/app/wechat/id414478124?l=en");
      } else {
        SmartDialog.showToast("已经是最新版本。");
      }
    }
  }

  static bool isUpdateApp(String selfVersion, String newsVersion) {
    print('isUpdateApp--selfVersion${selfVersion}--newsVersion${newsVersion}');
    return newsVersion.compareTo(selfVersion) > 0;
  }

  static Future<String> android() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.version;
  }

  static Future<String> ios() async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    IosDeviceInfo iosDeviceInfo = await deviceInfo.iosInfo;
    return iosDeviceInfo.systemVersion ?? "";
  }

  void down() async {
    RUpgradeInstallType installType = RUpgradeInstallType.normal;
    NotificationVisibility notificationVisibility =
        NotificationVisibility.VISIBILITY_VISIBLE;
    NotificationStyle notificationStyle = NotificationStyle.planTime;

    Future<int?> _upgrade() async {
      var id = await RUpgrade.upgrade("",
          installType: installType,
          notificationStyle: notificationStyle,
          notificationVisibility: notificationVisibility,
          useDownloadManager: false);
      return id;
    }
  }

  UpdateDialog? dialog;

  double progress = 0.0;

  void registerProgress(){
    RUpgrade.stream.listen((DownloadInfo info){
      progress=(info.percent ??0.00)/100;
      print('registerProgress${progress}');
      print('registerProgress${info.toString()}');
      if (progress > 1.0001||info.status==DownloadStatus.STATUS_SUCCESSFUL) {
          dialog!.dismiss();
          progress = 0;
          SmartDialog.showToast("升级成功");
        } else {
          dialog!.update(progress);
        }
    });
  }

  void onUpdate(String url) async{
    print('onUpdate${url}');
    SmartDialog.showToast("APP在后台升级中，请稍等。");
    RUpgrade.stream.listen((DownloadInfo info){
      print("RUpgrade.stream${info.percent}");
    });
   var resp=await RUpgrade.upgrade(url,useDownloadManager: true);
   // if(resp!=null){
   //   dialog!.dismiss();
   //   progress = 0;
   //   SmartDialog.showToast("升级成功");
   // }else{
   //   SmartDialog.showToast("升级失败");
   // }
  }


  void customStyle(VersionBeanEntity bean) {
    if (dialog != null && dialog!.isShowing()) {
      return;
    }
    dialog = UpdateDialog.showUpdate(Get.context!!,
        width: 250,
        title: '是否升级到${bean.version}版本？',
        updateContent: bean.content,
        titleTextSize: 14,
        contentTextSize: 12,
        buttonTextSize: 12,
        topImage: Image.asset(R.assetsImgUpdateBgAppTop),
        extraHeight: 5,
        radius: 8,
        themeColor: const Color(0xFFFFAC5D),
        progressBackgroundColor: const Color(0x5AFFAC5D),
        isForce: true,
        updateButtonText: '升级',
        ignoreButtonText: '忽略此版本',
        enableIgnore: true, onIgnore: () {
          SmartDialog.showNotify(msg: '忽略', notifyType: NotifyType.failure);
          dialog!.dismiss();
        }, onUpdate: (){
          onUpdate(bean.fileUrl);
        });
  }
}
